<template>
    <div class="app-container">
        <el-form ref="searchForm" inline :model="searchForm" style="position:relative;">
            <div style="text-align: right;margin-bottom: 20px;"><el-button @click="addClick" type="primary">添加产品规格</el-button></div>
        </el-form>
        <el-table :data="tableData" border style="width: 100%;margin-bottom: 20px;">
            <el-table-column type="index" label="序号" width="50" align="center"></el-table-column>
            <el-table-column prop="specName" label="规格名称" align="center"></el-table-column>
            <!-- <el-table-column prop="valueType" :formatter="valueTypeFun" label="显示方式" align="center"></el-table-column>
            <el-table-column :formatter="tooltipFun" label="规格数据" align="center" show-overflow-tooltip></el-table-column> -->
            <el-table-column prop="description" label="规格描述" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column prop="createTime" label="创建时间" align="center" width="160"></el-table-column>
            <el-table-column label="操作" width="160" align="center" fixed="right">
                <template slot-scope="scope">
                    <el-button @click.stop="editClick(scope.row)" type="primary" plain size="mini">编辑</el-button>
                    <el-button @click.stop="delClick(scope.row)" type="danger" plain size="mini">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination @current-change="getList" layout="total, prev, pager, next, jumper" :total="pageData.totalElements"></el-pagination>
        <!-- 弹框 -->
        <el-dialog :visible.sync="showDialog" width="800px">
            <el-form ref="dataForm" :rules="rules" :model="dataForm" label-position="left" label-width="120px" style="margin: 0px 50px;">
                <el-form-item label="规格名称：" prop="specName">
                    <el-input v-model="dataForm.specName" placeholder="必填项。请输入与规格名称"></el-input>
                </el-form-item>
                <el-form-item label="规格描述：" prop="description">
                    <el-input v-model="dataForm.description" type="textarea" :rows="4" placeholder="必填项。请输入规格描述"></el-input>
                </el-form-item>
                <el-form-item label="显示类型：" prop="valueType">
                    <el-radio v-model="dataForm.valueType" label="1">文字</el-radio>
                    <el-radio v-model="dataForm.valueType" label="2">图片</el-radio>
                </el-form-item>
                <el-button @click="addSKU" type="primary" size="mini" plain icon="el-icon-circle-plus-outline">添加规格</el-button>
                <el-row v-if="dataForm.productSpecValueEntityList.length != 0" style="padding: 15px 0px 10px;text-align: center;">
                    <el-col :span="10">规格值</el-col>
                    <el-col :span="10">提示信息</el-col>
                    <el-col :span="4">操作</el-col>
                </el-row>
                <el-row v-for=" (item, index ) in dataForm.productSpecValueEntityList" :key="index" style="text-align: center;margin-bottom: 10px;">
                    <el-col :span="10" style="padding: 9px 15px 0;">
                        <el-input v-if="dataForm.valueType == 1" v-model="item.specValue" placeholder="请输入产品规格值"></el-input>
                        <el-upload v-if="dataForm.valueType == 2" class="avatar-uploader" action="" :http-request="UploadImage" :show-file-list="false" :before-upload="beforeAvatarUpload" style="margin-top: -13px;" >
                            <img v-if="item.specValue" @click="nowUpload(index)" :src="showPicArr[index]" class="avatar" width="100%">
                            <i v-else @click="nowUpload(index)" class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                    </el-col>
                    <el-col :span="10" style="padding: 9px 15px 0;"><el-input v-model="item.tooltip" placeholder="请输入产品规格提示信息"></el-input></el-col>
                    <el-col :span="4"><el-button @click="delSku(index)" type="danger" plain size="mini" style="margin-top: 13px;">删除</el-button></el-col>
                </el-row>
                <el-form-item style="text-align: center;margin-top: 20px;">
                    <el-button @click="addSubmit('dataForm')" type="primary">保存</el-button>
                    <el-button @click="cancelClick('dataForm')">取消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
</template>
<script>
import { addSpec, findSpec, editSpec, detailSpec, delSpec } from '@/api/product/product-specification'
import { uploadPic, getPic } from '@/api/uploadPic'
import { getCookie, setCookie } from '@/utils/auth'
export default {
    name: 'Spec',
    data() {
        return{
            tableData: [],
            nowTit: '',
            nowId: '',
            showDialog: false,
            dataForm: {
                specName: '',
                description: '',
                valueType: '1',  //1文字   2图片
                productSpecValueEntityList: []
            },
            rules: {
                specName: [
                    { required: true, message: '请输入', trigger: 'blur' }
                ],
                // description: [
                //     { required: true, message: '请输入', trigger: 'blur' }
                // ],
            },
            searchForm: {},
            nowPage: 0,
            pageSize: 10,
            imageUrl: '',
            formData: {},
            popStatus: 0,  //0为添加，1为修改
            pageData: {},
            uploadInd: 0,
            showPicArr: [],
        }
    },
    methods: {
        //默认函数
        init(){
            let _this = this;
            //获取列表信息
            findSpec(this.nowPage, this.pageSize).then(response => {
                if(response.code == 200){
                    _this.pageData = response.object;
                    _this.tableData = response.object.content;
                }else{
                    this.$message.error(response.message);
                }
            })
        },
        //添加
        addClick(){
            this.popStatus = 0;
            this.showDialog = true;
            this.dataForm.specName = '';
            this.dataForm.valueType = '1';
            this.dataForm.description = '';
            this.dataForm.productSpecValueEntityList = [];
            if(this.dataForm.id){
                delete this.dataForm.id;
            }
        },
        //提交添加
        addSubmit(formName){
            let _this = this;
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    //判断 productSpecValueEntityList里value不能为空且productSpecValueEntityList不能为空
                    // if(_this.dataForm.productSpecValueEntityList.length == 0){
                    //     this.$message.error('请添加规格值');
                    //     return
                    // }else{
                    //     for (let key=0;key<_this.dataForm.productSpecValueEntityList.length;key++) {
                    //         if(_this.dataForm.productSpecValueEntityList[key].specValue == ''){
                    //             this.$message.error('请输入规格值');
                    //             return
                    //         }
                    //         if(_this.dataForm.productSpecValueEntityList[key].tooltip == ''){
                    //             this.$message.error('请输入提示信息');
                    //             return
                    //         }
                    //     }
                    // }
                    //提交
                    if(_this.popStatus == 0){  //添加
                        addSpec(_this.dataForm).then(response => {
                            if(response.code == 200){
                                this.$message.success(response.message);
                                _this.init();
                                _this.showDialog = false;
                            }else{
                                this.$message.error(response.message);
                            }
                        })
                    }else if(_this.popStatus == 1){  //修改
                        _this.dataForm.id = _this.nowId;
                        editSpec(_this.dataForm).then(response => {
                            if(response.code == 200){
                                this.$message.success(response.message);
                                _this.init();
                                _this.showDialog = false;
                            }else{
                                this.$message.error(response.message);
                            }
                        })
                    }
                    
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        //删
        delClick(row){
            let _this = this;
            this.$confirm('确定删除 '+row.specName+' 吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                //删除
                delSpec(row.id).then(response => {
                    if(response.code == 200){
                        this.$message.success(response.message);
                        _this.init();
                    }else{
                        this.$message.error(response.message);
                    }
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                });          
            });
        },
        //编辑
        editClick(row){
            const _this = this;
            _this.popStatus = 1;
            _this.nowId = row.id;
            _this.dataForm.productSpecValueEntityList = [];
            detailSpec(row.id).then(response => {
                if(response.code == 200){
                    _this.dataForm.specName = response.object.specName;
                    _this.dataForm.valueType = response.object.valueType.toString();
                    _this.dataForm.description = response.object.description;
                    const list = response.object.productSpecValueEntityList;
                    if(list){
                        if(response.object.valueType == 2){  //图片
                            for(let i=0;i<list.length;i++){
                                _this.dataForm.productSpecValueEntityList.push({specValue: list[i].specValue,tooltip: list[i].tooltip});
                                getPic(list[i].specValue).then(res => {
                                    if(res.code == 200){
                                        _this.showPicArr.push(res.object);
                                    }else{
                                        _this.$message.error(res.message);
                                    }
                                })
                            }
                        }else if(response.object.valueType == 1){  //文字
                            for(let i=0;i<list.length;i++){
                                _this.dataForm.productSpecValueEntityList.push({specValue: list[i].specValue,tooltip: list[i].tooltip});
                            }
                        }
                    }
                }else{
                    this.$message.error(response.message);
                }
            })
            this.showDialog = true;
        },
        //取消
        cancelClick(formName){
            this.showDialog = false;
            this.$refs[formName].resetFields();
        },
        //自定义上传
        UploadImage(param){
            const _this = this;
            let formData = new FormData();
            formData.append('photoFile', param.file);
            formData.append('dir', 'ProductSpecification');
            formData.append('fileType', '1');
            uploadPic(formData).then(response => {
                if(response.code == 200){
                    //获取阿里云图片
                    getPic(response.object.saveImage).then(res => {
                        if(res.code == 200){
                            _this.showPicArr[this.uploadInd] = res.object;
                            _this.dataForm.productSpecValueEntityList[this.uploadInd].specValue = response.object.saveImage;
                        }else{
                            this.$message.error(res.message);
                        }
                    })
                }else{
                    this.$message.error(response.message);
                }
            })
        },
        //准备上传
        beforeAvatarUpload(file){
            const isJPG = file.type;
            const isLt2M = file.size / 1024 / 1024 < 4;
            if(((isJPG === 'image/jpeg') || (isJPG === 'image/png') || (isJPG === 'image/jpg') || (isJPG === 'image/gif') || (isJPG === 'image/JPEG') || (isJPG === 'image/PNG') || (isJPG === 'image/JPG') || (isJPG === 'image/GIF')) == false){
                this.$message.error('上传图片只能是 jpeg、png、jpg、gif 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传图片大小不能超过 4MB!');
            }
            return isJPG && isLt2M;
        },
        nowUpload(index){
            this.uploadInd = index;
        },
        //分页
        getList(val) {
            this.nowPage = val - 1;
            this.init();
        },
        //添加规格
        addSKU(){
            this.dataForm.productSpecValueEntityList.push({specValue: '', tooltip: ''});
        },
        //删除规格
        delSku(ind){
            this.dataForm.productSpecValueEntityList.splice(ind,1);
            this.showPicArr.splice(ind,1);
        },
        valueTypeFun(row){
            if(row.valueType == 1){
                return '文字'
            }else if(row.valueType == 2){
                return '图片'
            }
        },
        tooltipFun(row){
            let list = row.productSpecValueEntityList;
            if(list){
                let str = '';
                for(let i=0;i<list.length;i++){
                    str += '【' + list[i].tooltip + '】';
                }
                return str;
            }
        },
    },
    mounted(){
        this.init()
    }
}
</script>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 60px;
    height: 60px;
    line-height: 60px;
    text-align: center;
  }
  .avatar {
    width: 60px;
    height: 60px;
    display: block;
  }
</style>